import React, { useEffect, useState } from 'react'
import { Button, NavBar, Icon, InputItem, WhiteSpace, WingBlank, Modal, Toast } from 'antd-mobile'
import { verify_phone } from '../../api/register/verify_phone'
import {sendCode } from '../../api/login/sendCode'


let phone
export default function RegisterPhone(props) {


    const [isDisabled, setisDisabled] = useState(true)

    useEffect(() => {
        Modal.alert('注册协议及隐私政策', <p>在您注册成为硅谷用户的过程中，您需要完成我们的注册流程并通过点击同意的形式在线签署以下协议，<span className="secret-text">请您务必仔细阅读、充分理解协议中的条款内容后再点击同意（尤其是以粗体并下划线标识的条款，因为这些条款可能会明确您应履行的义务或对您的权力有所限制）：</span> <br />《硅谷用户注册协议》<br />《硅谷隐私政策》</p>, [
            { text: '不同意', onPress: () => props.history.push('/login') },
            {
                text: '同意', 
            },
        ])
    }, [])

    function handleChange(val) {
        // console.log(val);
        if (/^1[3-9]\d{9}$/.test(val)) {
            setisDisabled(false)
        } else {
            setisDisabled(true)
        }
        phone = val
        props.savePhone(phone)
    }

    async function handleClick() {
        const result = await verify_phone(phone)
        // console.log(data);
        await sendCode(phone)
        // console.log(code);
        if (result.data.success) {

            Modal.alert(undefined, '我们将发送验证码给以下的号码：' + phone, [
                { text: '不同意', },
                { text: '同意', onPress: () => {
                    props.history.push('/registerVerifyCode')
                    localStorage.setItem('msg',phone)
                } },
            ])

        } else {
            Toast.info(result.data.message, 1);

            setTimeout(() => {
                props.history.push('/login')
            }, 1000);
        }
    }


    return (
        <div className="login-wrap">

            <NavBar
                mode="light"
                icon={<Icon type="left" color="black" />}
                onLeftClick={() => props.history.push('/login')}
            >硅谷注册登录</NavBar>
            <WhiteSpace size="sm" />
            <WingBlank size="lg">
                <InputItem
                    clear
                    placeholder="请输入手机号"
                    onChange={handleChange}
                >
                    <div className="login-icon">+86<Icon type="down" /></div>
                </InputItem>
                <WhiteSpace size="xl" />
                <WingBlank size="lg">
                    <Button type="warning" disabled={isDisabled} className="login-btn" onClick={handleClick}>登录</Button>
                </WingBlank>
            </WingBlank>
        </div>
    )
}
